package cn.ciis.basic.interceptor;

import cn.ciis.basic.kit.CiisKit;
import cn.ciis.basic.kit.J2CacheKit;
import cn.ciis.basic.model.Account;
import cn.ciis.sys.login.LoginService;
import cn.ciis.sys.setting.SettingAdminService;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.security.token.SSOToken;
import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import net.oschina.j2cache.CacheObject;


/**
 * 从 cookie 中获取 sessionId，如果获取到则根据该值使用 LoginService 得到登录的 Account 对象 ---> loginAccount，供后续的流程使用
 *
 * <p>注意：将此拦截器设置为全局拦截器，所有 action 都需要
 *
 * @author 冉志林
 */
public class LoginSessionInterceptor implements Interceptor {

  @Inject
  LoginService loginSrv;

  @Inject
  SettingAdminService settingAdminService;

  @Override
  public void intercept(Invocation inv) {
    Account loginAccount = null;
    Controller c = inv.getController();
    SSOToken ssoToken = null;
    inv.getController().set("resource_version",CiisKit.RESOURCE_VERSION);//设置静态资源版本
    try {
      ssoToken = SSOHelper.getSSOToken(inv.getController().getRequest());
    }catch (Exception e){
      LogKit.error("错误的登录令牌");
    }

    if (ssoToken != null && StrKit.notBlank(ssoToken.getIssuer())) {
      String sessionId = ssoToken.getIssuer();
      loginAccount = loginSrv.getLoginAccountWithSessionId(sessionId);
      if (loginAccount == null) {
        String loginIp = CiisKit.getRealIp(c.getRequest());
        loginAccount = loginSrv.loginWithSessionId(sessionId, loginIp);
      }
      if (loginAccount != null) {
        // 用户登录账号
        c.setAttr(LoginService.LOGIN_ACCOUNT_CACHE_NAME, loginAccount);
        CacheObject cacheObject = J2CacheKit.get("setting", "system_setting", s -> {
          return settingAdminService.findMaxId();
        }, true);
        if(null != cacheObject && null != cacheObject.getValue()){
          c.setAttr("setting", cacheObject.getValue());
        }
      } else {
        // cookie 登录未成功，证明该 cookie 已经没有用处，删之
        c.removeCookie(LoginService.SESSION_ID_NAME);
      }
    }
    inv.invoke();
  }
}
